package com.durunmin;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTwo {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(80);

        System.out.println("服务器准备就绪~");
        System.out.println("服务器信息："+serverSocket.getInetAddress()+" P: "+serverSocket.getLocalPort());
        System.out.println("服务器信息："+serverSocket.getLocalSocketAddress()+" P: "+serverSocket.getLocalPort());
        while (true){
            Socket socket = serverSocket.accept();
            ClientHandler clientHandler = new ClientHandler(socket);
            clientHandler.start();
        }

    }


    public static class ClientHandler extends Thread{

        private Socket socket;

        public ClientHandler(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            super.run();
            System.out.println("新客户端连接："+socket.getInetAddress()+" P: "+socket.getPort());
            try {
                //获取输入流
                InputStream socketInput = socket.getInputStream();
                //BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                //构建输出流
                PrintStream printStream = new PrintStream(socket.getOutputStream());

                int num = socketInput.available();
                System.out.println("num:"+num);

                byte[] bytes = new byte[num];
                socketInput.read(bytes);
                String string = new String(bytes);
                System.out.println(string);

                printStream.println("HTTP/1.1 200 OK\r\n" +  //响应头第一行
                        "Content-Type: text/html; charset=utf-8\r\n" +  //简单放一个头部信息
                        "\r\n");
                String body = "{\"responseCode\":\"000000\",\"responseBody\":\"123\"}";
                printStream.println(body);

                //socketInput.close();
                //printStream.close();
                Thread.sleep(100000);
            } catch (IOException e) {
                System.out.println("连接异常断开");
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            System.out.println("客户端已退出："+socket.getInetAddress()+" P: "+socket.getPort());


        }
    }
}
